<template>
  <div class="loginContainer">
    <el-form label-width="100px" :model="userinfo">
      <el-form-item label="用户名">
        <el-input v-model="userinfo.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="userinfo.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
        <el-button type="primary" @click="signIn">注册</el-button>
        <el-button type="primary" @click="getUserList">获取用户</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { LOGIN, SINGIN, GETUSERLIST } from "../utils/url";
// import { useRouter } from "vue-router";
const currentInstance = getCurrentInstance();
const { $http, $message } = currentInstance.appContext.config.globalProperties;
// const router = useRouter();
const userinfo = ref({
  username: "",
  password: "",
});
const userList = ref([]);
const login = async () => {
  try {
    const { status, accessToken, refreshToken } = await $http(
      LOGIN,
      "post",
      userinfo.value
    );
    console.log("🚀 ~ login ~ status:", status);

    if (status === 0) {
      // 登录成功，存储token, 跳转到首页
      localStorage.setItem("accessToken", accessToken);
      localStorage.setItem("RefreshToken", refreshToken);
      // router.push("/home");
    } else {
      // 处理其他状态
      console.error("Login failed:", status);
    }
  } catch (error) {
    // 处理请求错误
    console.error("Login request failed:", error);
  }
};
const signIn = async () => {
  try {
    const { status, message } = await $http(SINGIN, "post", userinfo.value);
    console.log("🚀 ~ signIn ~ status, message:", status, message);

    if (status === 0) {
      $message.success(message);
    } else {
      // 处理其他状态
      console.error("signIn failed:", status);
    }
  } catch (error) {
    // 处理请求错误
    console.error("signIn request failed:", error);
  }
};
const getUserList = async () => {
  try {
    const res = await $http(GETUSERLIST, "post");
    console.log("🚀 ~ getUserList ~ res :", res);
    if (res.status == 0) {
      userList.value = res.data;
    }
  } catch (error) {
    console.log("🚀 ~ getUserList ~ error:", error);
  }
};
</script>

<style  scoped>
.loginContainer {
  margin: 100px auto 0;
  width: 500px;
  height: 500px;
}
</style>